using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Vector2 = System.Numerics.Vector2;

public enum BattleState
{
    Start,PlayerTurn,EnemyTurn,Victory,Failure
}

public class BattleSystem : Singleton<BattleSystem>
{
    public BattleState battleState;

    public Monster monster;

    public Player player;

    private PlayerController playerController;

    //怪物位于玩家的哪个方向
    public Direction monsterDirection;
    //玩家位于怪物的哪个方向
    public Direction playerDirection;
    
    // Start is called before the first frame update
    void Start()
    {
        battleState = BattleState.Start;
        player = GameManager.Instance.player.GetComponent<Player>();
        playerController = player.GetComponent<PlayerController>();
    }

    public void StartBattle()
    {
        GameManager.Instance.player.GetComponent<PlayerController>().playerControls.Gameplay.Disable();
        battle();
    }

    public void SetMonster(Monster monster,Direction direction)
    {
        this.monster = monster;
        this.monsterDirection = direction;
        
        Direction temp = Direction.Left;
        switch (direction)
        {
            case Direction.Left:
                temp = Direction.Right;
                break;
            case Direction.Down:
                temp = Direction.Up;
                break;
            case Direction.Right:
                temp = Direction.Left;
                break;
            case Direction.Up:
                temp = Direction.Down;
                break;
        }

        playerDirection = temp;
    }

    /// <summary>
    /// 开始战斗
    /// </summary>
    private void battle()
    {
        battleState = BattleState.Start;
        StartCoroutine(PlayerBattle());
        StartCoroutine(MonsterBattle());
    }

    private IEnumerator MonsterBattle()
    {
        while (player.IsAlive() && monster.IsAlive())
        {
            monster.Attack(player,playerDirection);
            yield return new WaitForSeconds(monster.monsterDetailSO.attackInterval);
        }
        if (player.IsAlive())
        {
            battleState = BattleState.Victory;
            GameManager.Instance.player.GetComponent<PlayerController>().playerControls.Gameplay.Enable();
        }
        else
        {
            battleState = BattleState.Failure;
        }
    }

    private IEnumerator PlayerBattle()
    {
        while (player.IsAlive() && monster.IsAlive())
        {
            player.Attack(monster,monsterDirection);
            yield return new WaitForSeconds(player.attackInterval);
        }
        if (player.IsAlive())
        {
            battleState = BattleState.Victory;
            GameManager.Instance.player.GetComponent<PlayerController>().playerControls.Gameplay.Enable();
        }
        else
        {
            battleState = BattleState.Failure;
        }
    }
    
}
